#include "dialog.h"
#include "ui_dialog.h"
#include <QTextTable>
#include <QScrollBar>
#include <QtDebug>
#include <QTime>
Dialog::Dialog(QWidget *parent)
    : QDialog(parent), ui(new Ui::DialogClass),option(new optionDialog),isConnected(false)
{
    ui->setupUi(this);
    ui->lineEdit->setFocusPolicy(Qt::StrongFocus);
    ui->textEdit->setFocusPolicy(Qt::NoFocus);
    ui->textEdit->setReadOnly(true);
    ui->optionButton->setFocusPolicy(Qt::NoFocus);

    this->setWindowTitle(tr("公交定位网络测试"));
    connect(ui->optionButton,SIGNAL(clicked()),this,SLOT(setOption()));
    connect(option,SIGNAL(optionChanged(bool,QHostAddress*,int)),this,SLOT(getOption(bool,QHostAddress*,int)));
    connect(ui->lineEdit,SIGNAL(returnPressed()),this,SLOT(returnPressed()));
    //tcpclient 作为客户端时候的连接
    connect(&tcpClient,SIGNAL(connected()),this,SLOT(connectedToServer()));
    //connect(&tcpClient,SIGNAL(bytesWritten()),this,SLOT(messageSended()));//数据发送成功
    connect(&tcpClient,SIGNAL(readyRead()),this,SLOT(messageArrived())); //有数据到达;
    //server有新的连接
    connect(&tcpServer,SIGNAL(newConnection ()),this,SLOT(acceptConnection()));
    tableFormat.setBorder(0);

}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::setOption()
{



    option->move( this->x() +60,this->y()+80);
    option->show();
    //qDebug()<<"after show";


}

void Dialog::getOption(bool isClient,QHostAddress *ip,int port)
{
    this->isClient = isClient;
    //this->ip = ip;
    this->port = port;
    if(ip->isNull())
        return;
    this->ip = QHostAddress(ip->toString());

    if(isClient)
    {
        //连接服务器
       ui->optionButton->setText(tr("客户端"));
       tcpClient.connectToHost(this->ip ,port);
       qDebug() <<"connect to host"<<ip->toString()<<port;

    }

    else
    {
        //如果是服务器就开始监听

        ui->optionButton->setText(tr("服务器"));
        tcpServer.listen(QHostAddress::Any,port);
        qDebug()<<"start listen!";





    }
    //ui->optionButton->setEnabled(false);
}
void Dialog::returnPressed()
{
    //当按下enter键发送信息出去后.
    //1.获取消息
    //2.将消息发送到目标地址
    //3.将消息在本地显示
    QString text = ui->lineEdit->text();

    //判断输入的是否为空字符串
    if(text.isEmpty())
        return;
    ui->lineEdit->clear();
    appendMessage(tr("你说:"),text);
    QByteArray out(text.toAscii());

    if(isClient && isConnected)
    {
        tcpClient.write(out);

    }
    if(!isClient &&isConnected)
    {
        qDebug()<<tr("server write")<<out;
        //向所有的连接用户发送信息
       // tcpServerConnection->write(out);
        //这里做实验就随机产生四个数字
        int carNumToOrder[10]= {1,5,7,13,14,21,25,30,32,101 };
        int msg[4];
        char des[16];
        //msg[0] = qAbs(qrand()%10);
        QTime time;
        time = QTime::currentTime();
        msg[0] = carNumToOrder[qAbs(qrand()%10)];
        msg[1] = qAbs(qrand()%200);
        msg[2] = time.hour();
        msg[3] = time.minute();
        out.append(QString::number(msg[0],10));
        out.append(QString::number(msg[1],10));
        out.append(QString::number(msg[2],10));
        out.append(QString::number(msg[3],10));
        //将数字转换为16个字节的序列

        memcpy((void*)des,(void*)msg,16);
        qDebug()<<msg[0]<<msg[1]<<msg[2]<<msg[3];
        foreach(QTcpSocket *socket,connectedSockets)
        {
            //socket->write(out);
             char *temp = "12322345";
             socket->write(des,16);

            // socket->write(out);
        }

    }


}

void Dialog::appendMessage(const QString &from,const QString &message)
{
    if(from.isEmpty() || message.isEmpty())
        return;
    QTextCursor cursor(ui->textEdit->textCursor());
    cursor.movePosition(QTextCursor::End);

    QTextTable *table = cursor.insertTable(1,2,tableFormat);
    table->cellAt(0,0).firstCursorPosition().insertText("<"+ from + ">");
    table->cellAt(0,1).firstCursorPosition().insertText(message);
    QScrollBar *bar = ui->textEdit->verticalScrollBar();
    bar->setValue(bar->maximum());


}

void Dialog::messageArrived()
{
    //服务器和客户端做不同的处理，服务器要获取ip
    QByteArray in;
    if(isClient)
    {
           in = tcpClient.readAll();
           appendMessage(tr("server"),QString(in));
    }

    else //服务器端
    {


           foreach(QTcpSocket *socket,connectedSockets)
          {
               //如果有数据就显示
               qDebug()<<socket->state();
               if(socket->state() == QAbstractSocket::UnconnectedState )
               {
                   qDebug()<<tr("断开连接").arg(socket->peerAddress().toString());
                   connectedSockets.removeAt(connectedSockets.indexOf(socket));
               }


              if(socket->state() == QAbstractSocket::ConnectedState && socket->bytesAvailable() >= 0 )
              {
                 // in = socket->readAll();
                  int ret;
                  char msg[8];
                  ret = socket->read(msg,8);
                  if(ret < 8)
                      return ;
                  int num[2];
                  memcpy(&num,msg,8);
                  //sendMsg(num[0],num[1],socket);
                 foreach(QTcpSocket *socket1,connectedSockets)
                  {
                       if(socket1 != socket)
                        sendMsg(num[0],num[1],socket1);
                   }

              }


          }

    }
}
//连接到服务器成功
void Dialog::connectedToServer()
{
    qDebug()<<tr("连接成功!");
    isConnected = true;

}

void Dialog::acceptConnection()
{
        QTcpSocket * tcpSocket = new QTcpSocket( );
        tcpSocket = tcpServer.nextPendingConnection();
       // qDebug() <<tr("peer ip = %1").arg(tcpServerConnection->peerAddress().toString());
        isConnected = true;
        //connect(tcpServerConnection,SIGNAL(readyRead()),this,SLOT(messageArrived()));
        connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(messageArrived()));

        qDebug() << tr("接受连接");
        //peers.insert(tcpSocket->peerAddress(),tcpSocket);
        connectedSockets.append(tcpSocket);
}

void Dialog::sendMsg(int carnum,int place,QTcpSocket* socket)
{
         int carNumToOrder[10]= {1,5,7,13,14,21,25,30,32,101 };
        QTime time;
        int msg[4];
        char des[16];
        time = QTime::currentTime();
        msg[0] = carNumToOrder[carnum];
        msg[1] = qAbs(place);
        msg[2] = time.hour();
        msg[3] = time.minute();

        //将数字转换为16个字节的序列

        memcpy((void*)des,(void*)msg,16);
        qDebug()<<msg[0]<<msg[1]<<msg[2]<<msg[3];
        socket->write(des,16);
        appendMessage(tr("send to  %1:").arg(socket->peerAddress().toString()),
                                tr("车号%1 位置%2").arg(msg[0]).arg(msg[1]));
}




